<script setup lang="ts">
import { onMounted, provide, reactive, ref } from 'vue'
import { SearchBox } from '@/components/common/index.js'
import { useMainInfoStore, useDictOptionStore } from '@/stores'
import type { Enterprise } from '@/stores/modules/main-info/helper'
import type { DictOption, DictOptionItem } from '@/stores/modules/dict-option/helper'
import type { TableColumnScopedSlot } from './helper'
import PopupBox from './PopupBox/index.vue'

// Create variable for responsive
const isLoading = reactive({
  tableData: true,
  queryBarData: true,
  deleteTableData: false,
  deleteTableRowData: false
})
const selectionRow = ref<Array<Enterprise>>([])
const queryConditions = ref<{ [key: string]: DictOptionItem }>({
  enterprise_name: {
    dictCode: 'enterprise_name',
    dictName: `主体名称`,
    type: 'input'
  }
})
const inputConditions = ref<DictOption>()

// Get store object
const mainInfoStore = useMainInfoStore()
const dictOptionStore = useDictOptionStore()

// Provide variable for children
const children = ref<{ showPopup: boolean; id?: number; boxType?: 'modify' | 'create' }>({
  showPopup: false
})

// After mounted events
onMounted(async () => {
  await handleInitQueryConditions()
  await handleQueryData()
})

// Init query conditions
const handleInitQueryConditions = async () => {
  isLoading.queryBarData = true
  Object.assign(
    queryConditions.value,
    await mainInfoStore.querySearchConditions([`industry`, `principalType`])
  )
  isLoading.queryBarData = false
}

// Fetch query data
const handleQueryData = async (conditions?: DictOption) => {
  isLoading.tableData = true
  await mainInfoStore.query(conditions)
  inputConditions.value = conditions
  isLoading.tableData = false
}

// Create single new data
const handleCreateData = () => {
  // todo 创建主体数据
  children.value = {
    showPopup: true,
    boxType: 'modify'
  }
}

// Update single data
const handleUpdateData = (newData: Enterprise) => {
  console.log(newData)
}

// Batch delete data
const handleDeleteData = async () => {
  const _rows = selectionRow.value
  if (_rows) {
    isLoading.deleteTableData = true
    const ids = _rows.map((it) => it?.id).filter((id) => id !== undefined) as Array<number>
    if (await mainInfoStore.deleteByIds(ids)) {
      await handleQueryData()
    }
    isLoading.deleteTableData = false
  }
}

// Table row actions
const _currentRowIndex = ref(-1)
const handleRowDataAction = async (
  scope: TableColumnScopedSlot<Enterprise>,
  type: 'modify' | 'delete'
) => {
  scope.row.isLoading = true
  switch (type) {
    case 'delete':
      await mainInfoStore.deleteById(scope.row.id)
      await handleQueryData()
      break
    case 'modify':
      children.value = {
        id: scope.row.id,
        showPopup: true,
        boxType: 'modify'
      }
      _currentRowIndex.value = scope.$index
      break
  }
  scope.row.isLoading = false
}

// Callback for current page number update
const handleCurrentChange = async (value: number) => {
  await mainInfoStore.updateCurrentPage(value, inputConditions.value)
}

// Callback for single page number update
const handleSizeChange = async (value: number) => {
  await mainInfoStore.updatePageCount(value, inputConditions.value)
}

// Callback for select row change
const handleSelectionChange = (selection: Array<Enterprise>) => {
  selectionRow.value = selection
}

const handleCancel = () => {
  children.value = { showPopup: false }
}

const handleSave = (data: Enterprise) => {
  // console.log('保存', data)
  mainInfoStore.createOrUpdate(data, _currentRowIndex.value)
  handleCancel()
}
</script>

<template>
  <!-- Search box -->
  <SearchBox
    :conditions="queryConditions"
    :showSearchBar="mainInfoStore.showSearchBar"
    @query-event="handleQueryData"
    :isConfirmButtonLoading="isLoading.tableData"
  />
  <!-- Action bar -->
  <el-row class="table-action">
    <el-col :span="12">
      <el-button type="primary" icon="plus" plain @click="handleCreateData">新增</el-button>
      <el-popconfirm
        :title="'确定要删除【' + selectionRow.length + '/条】数据吗？'"
        @confirm="handleDeleteData"
        width="200px"
      >
        <template #reference>
          <el-button
            type="danger"
            icon="delete"
            plain
            :disabled="!selectionRow.length"
            :loading="isLoading.deleteTableData"
          >
            {{ isLoading.deleteTableData ? '删除中' : '删除' }}
          </el-button>
        </template>
      </el-popconfirm>
    </el-col>
    <el-col :span="12">
      <el-button
        icon="search"
        circle
        @click="() => (mainInfoStore.showSearchBar = !mainInfoStore.showSearchBar)"
      />
      <el-button icon="refresh" circle @click="handleQueryData" />
    </el-col>
  </el-row>

  <!-- Data render -->
  <el-row class="table-row">
    <el-table
      v-loading="isLoading.tableData"
      :data="mainInfoStore.enterpriseList"
      stripe
      max-height="calc(100vh - 265px)"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            type="primary"
            icon="edit"
            circle
            @click="handleRowDataAction(scope, 'modify')"
            :loading="scope.row?.isLoading"
          />
          <el-popconfirm
            :title="'确定要删除【' + scope.row.enterpriseName + '】吗？'"
            @confirm="handleRowDataAction(scope, 'delete')"
            width="200px"
          >
            <template #reference>
              <el-button type="danger" icon="delete" circle :loading="scope.row?.isLoading" />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
      <el-table-column prop="enterpriseName" label="主体名称" sortable />
      <el-table-column prop="principalType" label="主体类型" sortable>
        <template #default="scope">
          {{ dictOptionStore.convertCodeToDictName('principalType', scope.row.principalType) }}
        </template>
      </el-table-column>
      <el-table-column prop="industry" label="所属行业" sortable>
        <template #default="scope">
          {{ dictOptionStore.convertCodeToDictName('industry', scope.row.industry) }}
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址" sortable />
      <el-table-column prop="registrationDate" label="注册日期" sortable />
    </el-table>
  </el-row>

  <!-- Page component -->
  <el-row justify="end" class="pagination">
    <el-pagination
      :hide-on-single-page="true"
      :current-page="mainInfoStore.currentPage"
      layout="sizes, prev, pager, next, jumper, total"
      :total="mainInfoStore.totalCount"
      :page-size="mainInfoStore.pageCount"
      :page-sizes="mainInfoStore.pageCountList"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-row>

  <!-- Create or Modify components  -->
  <PopupBox
    :show="children.showPopup"
    :id="children.id"
    @cancel="handleCancel"
    @save="handleSave"
    :box-type="children.boxType"
  />
</template>

<style scoped lang="less">
// Table component styles
.table-row {
  overflow: auto;
}

.table-action {
  & .el-col:last-child {
    text-align: right;
  }

  margin-bottom: 10px;
}

// Page component styles
.pagination {
  margin-top: 20px;
}
</style>
